package compute

import (
	"gitee.com/amoyx/cloud-provider/pkg/cloud/huawei/models"
	ecsv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/model"
	regionv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/region"
)

type ECSGreeter interface {
	ECS(region string) ECSInterface
}

type ECSInterface interface {
	DescribeInstance(id string) (result models.EcsServerDetail, err error)
	ListServersByName(name string) (list []models.EcsServerDetail, err error)
	ListAllServers() (list []models.EcsServerDetail, err error)
}

type ecs struct {
	region string
	client *ecsv2.EcsClient
}

func newECS(c *Compute, region string) ECSInterface {
	v := &ecs{
		region: region,
	}
	_client := ecsv2.NewEcsClient(
		ecsv2.EcsClientBuilder().
			WithRegion(regionv2.ValueOf(region)).
			WithCredential(c.credentials).
			Build())
	v.client = _client
	return v
}

func (e *ecs) ListServersByName(name string) (list []models.EcsServerDetail, err error) {
	return e.query("", name)
}

func (e *ecs) DescribeInstance(id string) (result models.EcsServerDetail, err error) {
	list, err := e.query(id, "")
	if len(list) > 0 {
		result = list[0]
	}
	return
}

func (e *ecs) ListAllServers() (list []models.EcsServerDetail, err error) {
	return e.query("", "")
}

func (e *ecs) query(id string, name string) (list []models.EcsServerDetail, err error) {
	request := &model.ListServersDetailsRequest{}
	limitRequest := int32(1000)
	request.Limit = &limitRequest
	offsetRequest := int32(1)
	request.Offset = &offsetRequest
	if name != "" {
		request.Name = &name
	}
	if id != "" {
		request.ServerId = &id
	}
	response, err := e.client.ListServersDetails(request)
	if err != nil {
		return
	}

	for _, v := range *response.Servers {
		var address []string
		for key := range v.Addresses {
			for _, addr := range v.Addresses[key] {
				address = append(address, addr.Addr)
			}
		}
		var tags []string
		for _, tag := range *v.Tags {
			tags = append(tags, tag)
		}
		var sgs []string
		for _, sg := range v.SecurityGroups {
			sgs = append(sgs, sg.Id)
		}
		list = append(list, models.EcsServerDetail{
			Id:                v.Id,
			Name:              v.Name,
			HostId:            v.HostId,
			HostStatus:        v.HostStatus,
			Status:            v.Status,
			Created:           v.Created,
			Updated:           v.Updated,
			Progress:          *v.Progress,
			SecurityGroups:    sgs,
			Description:       *v.Description,
			Tags:              tags,
			AutoTerminateTime: v.AutoTerminateTime,
			Locked:            v.Locked,
			Addresses:         address,
		})
	}
	return
}
